$(document).ready(function(){
	
	// jQuery UI specific styles
	$('input[name=contact-birthdate]').datepicker({
		changeMonth: true,
		numberOfMonths: 1,
		yearRange: '-80:+00'
	});
	$('input:checkbox').click(function(){
		$(this).parent().parent().toggleClass('ui-state-highlight');
	});
	
	// Uploadify's options
	$('#contact-file-upload').uploadify({
		'uploader'  : 'inc/uploadify.swf',
		'script'    : 'process/upload_docs.php',
		'cancelImg' : 'css/img/cancel.png',
		'buttonImg'	: 'css/img/folder_add.png',
		'folder'    : 'data/docs',
		'auto'      : false,
		'multi'		: true,
		'wmode'		: 'transparent',
		'height'	: '16',
		'scriptData': { 'otype':'contact', 'id':$('input[name=contact-contactId]').val() },
		'onAllComplete'	: function(event,data){
			location.reload();
		}
	});
	
	// Case: deleting an activity's document
	$('a.delete-doc').click(function(){
		var e = $(this);
		$.ajax({
			type:	'POST',
			url:	'process/document_delete.php',
			data:	'id='+e.attr('href'),
			success: function(msg){
				if (msg != 'OK')
					alert(msg);
				else
					e.parent().parent().remove();
			}
		});
		return false;
	});

	// Case: seeing a contact's details
	$('a#details').click(function(){
		
		// Checking if we have a contact selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner un élément !');
			return false;
		}
		
		// Redirecting user to the contact
		$(this).attr('href', 'contacts.php?id='+checked.first().val()+'&operation=edit');
		return true;
	});
	
	// Case: deleting a contact batch
	$('a#delete').click(function(){
		
		// Checking rights
		if (check_credentials('contact_delete') != 'yes'){
			alert('Vous n\'avez pas le droit d\'effectuer cette opération !');
			return false;
		}
		
		// Checking if we have at least one contact selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// AJAXing deletion
		if (confirm('Êtes-vous sûr de vouloir supprimer '+checked.length+' élément(s) ?')) {
			var total = checked.length;
			showLoading();
			checked.each(function(){
				$.ajax({
					type:	'POST',
					url:	'process/contact_delete.php',
					data:	'id='+$(this).val(),
					success: function(msg){
						if (msg != 'OK')
							alert(msg);
						else
							checked.parent().parent().remove();
						addLoading(100/total);
						closeLoading();
					}
				});
			});
		}
		return false;
	});
	
	// Case: submitting a new (or edited) contact
	$('a#form-contact').click(function(){
		
		// Getting inputs
		var operation = $('input[name=contact-operation]'),
			id = $('input[name=contact-contactId]'),
			salutation = $('input[name=contact-salutation]'),
			lastname = $('input[name=contact-lastname]'),
			firstname = $('input[name=contact-firstname]'),
			birthdate = $('input[name=contact-birthdate]'),
			jobtitle = $('input[name=contact-jobtitle]'),
			email = $('input[name=contact-email]'),
			ad_name = $('input[name=address-name]'),
			ad_building = $('input[name=address-building]'),
			ad_number = $('input[name=address-number]'),
			ad_street = $('input[name=address-street]'),
			ad_city = $('input[name=address-city]'),
			ad_postalcode = $('input[name=address-postalcode]'),
			allFields = $([]).add(salutation).add(lastname).add(firstname).add(birthdate).add(jobtitle).add(email);
		
		// Checking rights
		if (check_credentials('contact_'+operation.val()) != 'yes'){
			alert('Vous n\'avez pas le droit d\'effectuer cette opération !');
			return false;
		}
		
		// Checking form validity
		allFields.removeClass('ui-state-error');
		var valid = true;
		valid = valid && check_length(lastname, 'Nom', 1, 255);
		valid = valid && check_length(firstname, 'Prénom', 1, 255);
		if (email.val().length > 0) valid = valid && check_regexp(email, rexp_mail, 'Format : user@provider.com');
		if (birthdate.val().length > 0) valid = valid && check_regexp(birthdate, rexp_date, 'Format de date : jj/mm/aaaa');
		if (ad_postalcode.val().length > 0) valid = valid && check_regexp(ad_postalcode, rexp_postal, 'Merci d\'indiquer un code postal français');
		
		// We have errors
		if (!valid)
			return false;

		// No error: AJAX processing
		showLoading();
		$.ajax({
			type:	'POST',
			url:	'process/contact_'+operation.val()+'.php',
			data:	'id='+id.val()+'&salutation='+salutation.val()+'&lastname='+lastname.val()+'&firstname='+firstname.val()+'&birthdate='+birthdate.val()+'&jobtitle='+jobtitle.val()+'&email='+email.val()+'&ad_name='+ad_name.val()+'&ad_building='+ad_building.val()+'&ad_number='+ad_number.val()+'&ad_street='+ad_street.val()+'&ad_city='+ad_city.val()+'&ad_postalcode='+ad_postalcode.val(),
			success: function(msg){
				addLoading(100);
				history.back();
			}
		});
		return false;
	});
	
	// Case: seeing a prorole's details
	$('a#details-prorole').click(function(){
		
		// Checking if we have a prorole selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner un élément !');
			return false;
		}
		
		// Redirecting user to the prorole
		$(this).attr('href', 'gotproroles.php?id='+checked.first().val()+'&operation=edit');
		return true;
	});
	
	// Case: deleting a prorole batch
	$('a#delete-prorole').click(function(){
		
		// Checking rights
		if (check_credentials('gotprorole_delete') != 'yes'){
			alert('Vous n\'avez pas le droit d\'effectuer cette opération !');
			return false;
		}
		
		// Checking if we have at least one contact selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// AJAXing deletion
		if (confirm('Êtes-vous sûr de vouloir supprimer '+checked.length+' élément(s) ?')) {
			checked.each(function(){
				$.ajax({
					type:	'POST',
					url:	'process/gotprorole_delete.php',
					data:	'id='+$(this).val(),
					success: function(msg){
						if (msg != 'OK')
							alert(msg);
						else
							checked.parent().parent().remove();
					}
				});
			});
		}
		return false;
	});
	
	// Case: seeing a studentactivity's details
	$('a#details-studentactivity').click(function(){
		
		// Checking if we have a studentactivity selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner un élément !');
			return false;
		}
		
		// Redirecting user to the studentactivity
		$(this).attr('href', 'gotstudentactivities.php?id='+checked.first().val()+'&operation=edit');
		return true;
	});
	
	// Case: deleting a studentactivity batch
	$('a#delete-studentactivity').click(function(){
		
		// Checking rights
		if (check_credentials('gotstudentactivity_delete') != 'yes'){
			alert('Vous n\'avez pas le droit d\'effectuer cette opération !');
			return false;
		}
		
		// Checking if we have at least one contact selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// AJAXing deletion
		if (confirm('Êtes-vous sûr de vouloir supprimer '+checked.length+' élément(s) ?')) {
			checked.each(function(){
				$.ajax({
					type:	'POST',
					url:	'process/gotstudentactivity_delete.php',
					data:	'id='+$(this).val(),
					success: function(msg){
						if (msg != 'OK')
							alert(msg);
						else
							checked.parent().parent().remove();
					}
				});
			});
		}
		return false;
	});
	
	// Case: merging contact
	$('a#merge').click(function(){
		
		// Checking if we have at least one contact selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// Merging each contact
		$.ajax({
			type:	'POST',
			url:	'ajax/load_models.php',
			success: function(msg) {
				var select = $('div#select_model');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var model = $('input:radio:checked');
							if (model.length > 0) {
								checked.each(function(){
									window.open('process/contact_merge.php?model='+model.first().val()+'&contact='+$(this).val());
								});
							}
							$(this).dialog('close');
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
		return false;
	});
	
	// Case: merging contact's gotprorole
	$('a#merge-prorole').click(function(){
		
		// Checking if we have at least one contact selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// Merging each gotprorole
		$.ajax({
			type:	'POST',
			url:	'ajax/load_models.php',
			success: function(msg) {
				var select = $('div#select_model');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var model = $('input:radio:checked');
							if (model.length > 0) {
								checked.each(function(){
									window.open('process/gotprorole_merge.php?model='+model.first().val()+'&gotprorole='+$(this).val());
								});
							}
							$(this).dialog('close');
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
		return false;
	});
	
	// Case: merging contact's studentactivity
	$('a#merge-studentactivity').click(function(){
		
		// Checking if we have at least one contact selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// Merging each studentactivity
		$.ajax({
			type:	'POST',
			url:	'ajax/load_models.php',
			success: function(msg) {
				var select = $('div#select_model');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var model = $('input:radio:checked');
							if (model.length > 0) {
								checked.each(function(){
									window.open('process/gotstudentactivity_merge.php?model='+model.first().val()+'&gotstudentactivity='+$(this).val());
								});
							}
							$(this).dialog('close');
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
		return false;
	});
	
	// Case: batching e-mails
	$('a#sendmail').click(function(){

		// Checking if we have at least one contact selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// Building destination
		var dest = '',
			none = 0;
		checked.each(function(){
			var mail = $(this).parent().next('td').next().next().text();
			if (mail.length > 0)
				dest = dest+mail+';';
			else
				none = none+1;
		});
		
		// Case: some contacts don't have e-mails referenced
		if (none > 0) {
			if (confirm('L\'adresse e-mail de certains contacts n\'est pas renseignée. Souhaitez-vous tout de même continuer ?')) {
				$(this).attr('href', 'mailto:'+dest);
				return true;
			}
		}
		else {
			$(this).attr('href', 'mailto:'+dest);
			return true;
		}
		return false;
	});
});